// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const xlsx = require('node-xlsx') //操作excel用的类库
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    let userData = await db.collection('song').aggregate()
      .match({
        time: _.and(_.gte(new Date(event.startTime + " 00:00:00")), _.lte(new Date(event.endTime + " 23:59:59")))
      })
      .sort({
        time: -1
      })
      .limit(10000)
      .end()
    let data = userData.list

    let dataCVS = '点歌列表' + event.startTime.replace(/\//g, "-") + '~' + event.endTime.replace(/\//g, "-") + '.xlsx' //excel表格名
    let allData = [] //定义储存数据
    let row = ['歌名', '歌手', '备注', '状态（0未审核，1通过，2拒绝）'] //表属性
    allData.push(row)

    //遍历数组
    for (let key in data) {
      let arr = []
      arr.push(data[key].title)
      arr.push(data[key].singer)
      arr.push(data[key].tip)
      arr.push(data[key].state)
      allData.push(arr)
    }

    //把数据保存到excel里
    var buffer = await xlsx.build([{
      name: "Sheet1",
      data: allData
    }])

    //把excel文件保存到云存储里
    return await cloud.uploadFile({
      cloudPath: 'exportSongList/' + dataCVS,
      fileContent: buffer //excel二进制文件
    })
  } catch (e) {
    return e
  }
}